import org.xml.sax.*;
import java.util.*;
import java.io.*;

public class XMLContentHandler implements ContentHandler {
	boolean open = false;
	boolean done = false;
	boolean sub_open = false;
	String currentNode = "";
	int count = 0;
	BufferedWriter out;
	
	XMLContentHandler() {
	}

	public void setDocumentLocator (Locator locator) { 
	}

	public void startDocument () throws SAXException  { 
		try {
			out = new BufferedWriter(new FileWriter("test-out.txt"));
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public void endDocument() throws SAXException  { 
		try {
			out.close();
		} catch (IOException e) {
		}
	}

	public void startPrefixMapping (String prefix, String uri) throws SAXException  {
	}

	public void endPrefixMapping (String prefix) throws SAXException  { 
	}

	public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException  { 
		String attr_class="";
		currentNode = localName;
		try {
			attr_class=atts.getValue("class");
		} catch (Exception ae) {
		}
		if (attr_class == null) {
			attr_class = "";
		}
		if (open == true && attr_class.equals("mainformat")) {
			sub_open = true;
		}
		if (localName.equals("table") && done == false) {
			open = true;
		}
		if (currentNode.equals("a") && sub_open == true) {
			String value = atts.getValue("href");
			if (count < 2) {
				try {
					out.write(value + "\t");
					if (count == 1) {
						out.newLine();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			count++;
		}
	}

	public void endElement (String uri, String localName, String qName) throws SAXException { 
		if (done == false && open == true && localName.equals("tr")) {
			count = 0;
			sub_open = false;
		}
		if (localName.equals("table") && done == false && open == true) {
			open = false;
			done = true;
			currentNode = "";
		}
	}

	public void characters (char ch[], int start, int length) throws SAXException { 
		String handle = "";
		if (currentNode.equals("td") && sub_open == true) {
			for (int i=start;i<(start+length);i++) {
				handle = handle + ch[i];
			}
			if (count < 2) {
				try {
					out.write(handle + "\t");
					if (count == 1) {
						out.newLine();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			count++;
		}
	}

	public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { 
	}

	public void processingInstruction (String target, String data) throws SAXException { 
	}

	public void skippedEntity (String name) throws SAXException { 
	}

}

